package com.sf.osms.dep.quartz;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.sf.novatar.cluster.IKeepAliveAndLockResolver;
import com.sf.osms.dep.biz.ICommonServiceBiz;
import com.sf.osms.dep.domain.Agent;
import com.sf.osms.dep.processor.builder.EventProcessorFactory;
import com.sf.osms.dep.processor.util.ExceptionUtils;

@DisallowConcurrentExecution
public class AgentJob implements Job {
	private static Logger logger = LoggerFactory.getLogger(AgentJob.class);
	private static final String APPLICATION_CONTEXT_KEY = "applicationContextKey";
	private  IKeepAliveAndLockResolver clusterSync;
	private ICommonServiceBiz commonRouteService;
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		//获取srping上下文
		ApplicationContext applicationContext = null;
		try {
			applicationContext = (ApplicationContext) context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
		} catch (SchedulerException e) {
			e.printStackTrace();
			logger.error("******取得spring的上下文出现异常******");
			return;
		}
		//获取同步对象
		clusterSync = applicationContext.getBean(IKeepAliveAndLockResolver.class);
		//获取路由服务对象
		commonRouteService = applicationContext.getBean(ICommonServiceBiz.class);
		ScheduleJob scheduleJob = (ScheduleJob)context.getMergedJobDataMap().get("agentInfo");
		String agentName = scheduleJob.getAgent().getName();
		Agent agent = commonRouteService.findAgentInfo(agentName);
		
		try {
			if(clusterSync.isLockedFor(agent.getName())){
				return;
			}
			
			boolean lock = clusterSync.getLockFor(agent.getName());
			if(!lock){
				return;
			} 
			logger.info("******代理 " + agent.getName() + "开始处理 "+Thread.currentThread().getName()+"******");
			EventProcessorFactory.getEventProcessor(agent, commonRouteService).processAgentEvent(agent);
			logger.info("******代理 " + agent.getName() + "处理 结束"+Thread.currentThread().getName()+"******");
		} catch (Exception e) {
			logger.error("******代理 " + agent.getName() + "异常******");
			logger.error(ExceptionUtils.getExceptionStackString(e));
		}finally{
			clusterSync.releaseLockFor(agent.getName());
		}
	}

}
